//
//  SchoolSelectView.m
//  Comma
//
//  Created by 刘轩博 on 15/1/17.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "CollegeRegisterView.h"
#import "CollegeTableViewCell.h"
#import "PinYinForObjc.h"
#import "ChineseInclude.h"
#import "RegisterModel.h"
@implementation CollegeRegisterView

- (instancetype)initWithExitImage:(NSString *)exitImg collegeText:(NSString *)collegeText
{
    self = [super initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    if (self) {
        if (exitImg) {
            [self createExitButtonWithImage:exitImg];
        }
        if (collegeText) {
            [self createCollegeFieldWithText:collegeText];
        }
        
        self.tViewArray = [NSMutableArray array];
        self.searchArray = [NSMutableArray array];
        self.schoolHeadInfo = [NSMutableDictionary dictionary];
        self.schoolInfo = [NSMutableDictionary dictionary];
    }
    return self;
}

#pragma mark - 创建控件
- (void)createExitButtonWithImage:(NSString *)image
{
    self.backgroundColor = [UIColor whiteColor];
    
    self.exitButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _exitButton.frame = CGRectMake(5, 30, 50, 50);
    [_exitButton setBackgroundImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
    
    [self addSubview:_exitButton];
}

- (void)createCollegeFieldWithText:(NSString *)text
{
    self.collegeField = [[UITextField alloc] initWithFrame:CGRectMake(16, 64, SCREEN_WIDTH - 16, 44)];
    _collegeField.placeholder = text;
    [_collegeField setFont:[UIFont fontWithName:@"Helvetica-Bold" size:14.0]];
    [_collegeField addTarget:self action:@selector(textFieldDidChanged:) forControlEvents:UIControlEventEditingChanged];
    [_collegeField setTextColor:TEXTERGRAY];
    [self addSubview:_collegeField];
    
    // 分割线
    [GlobalMethod drawLineWithStartPoint:CGPointMake(0, 108) EndPoint:CGPointMake(SCREEN_WIDTH, 108) inUIView:self];
}

// 回收键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self endEditing:YES];
}

#pragma mark - 创建tableView 显示搜索出来的大学名称
- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(16, 110, SCREEN_WIDTH - 16, SCREEN_HEIGHT - 110) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[CollegeTableViewCell class] forCellReuseIdentifier:@"collegeCell"];
    _tableView.bounces = NO;
    
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
    [self addSubview:_tableView];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 33.0f;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (self.searchArray.count != 0) {
        
        return [self.searchArray count];
    }
    else
    {
        return [self.tViewArray count];
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CollegeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"collegeCell"];
    // 设置cell的线消失
    cell.separatorInset = UIEdgeInsetsMake(0, 375, 0, 0);
    
    if (self.searchArray.count != 0) {
        RegisterModel *model = [self.searchArray objectAtIndex:indexPath.row];
        [cell.collegeName setText:model.name];
    }
    else
    {
        RegisterModel *model = [_tViewArray objectAtIndex:indexPath.row];
        [cell.collegeName setText:model.name];
        
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
#pragma mark - 这个地方 当我们用searchBar的时候  就给searchbar.text赋值
    if (self.searchArray.count != 0) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        RegisterModel *model = [self.searchArray objectAtIndex:indexPath.row];
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setValue:model.name forKey:@"name"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"COLLEGESELECTED" object:self userInfo:dic];

    }
    else
    {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        RegisterModel *model = [_tViewArray objectAtIndex:indexPath.row];
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setValue:model.name forKey:@"name"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"COLLEGESELECTED" object:self userInfo:dic];
        
        
    }
    
}


#pragma mark - ok
- (void)textFieldDidChanged:(id)sender
{
    
    
    
    UITextField *input = (UITextField *)sender;
    input.text = [input.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    self.searchArray = [[NSMutableArray alloc] init];
    //拼音（判断输入的是否是汉字，如果是拼音就走下面的方法）
    if (input.text.length>0&&![ChineseInclude isIncludeChineseInString:input.text]) {
        for (int i=0; i<_tViewArray.count; i++) {
            NSString *myKey = [NSString stringWithFormat:@"%d",i];
            //  包括汉字（判断数据里是否包含这个输入的拼音，如何判断：如果我的数据都是汉字 先把汉字转化为拼音  然后 看我汉字拼音里是否包含输入的拼音）
            if ([ChineseInclude isIncludeChineseInString:[self.schoolInfo objectForKey:myKey]]) {
                //把汉字转化为拼音（第一次 把汉字转化成的拼音全部存储到字典中，第二次输入就从字典里区比较，然后添加的是汉字model）
                NSString *tempPinYinStr = [PinYinForObjc chineseConvertToPinYin:[self.schoolInfo objectForKey:myKey]];
                //搜索拼音里是否包含我输入的字符
                NSRange titleResult=[tempPinYinStr rangeOfString:input.text options:NSCaseInsensitiveSearch];
                //如果包含 就添加到数组里
                if (titleResult.length>0) {
                    RegisterModel *model = [self.tViewArray objectAtIndex:i];
                    [self.searchArray addObject:model];
                }
                //这里是每个汉字的首字符搜索  如：bd  百度
                //这个是包含汉字的首字符 原理同上
                NSString *tempPinYinHeadStr = [PinYinForObjc chineseConvertToPinYinHead:[self.schoolInfo objectForKey:myKey]];
                //判断我汉字的拼音里是否包含 每个汉字的首字符 如果是 就添加到数组里
                NSRange titleHeadResult=[tempPinYinHeadStr rangeOfString:input.text options:NSCaseInsensitiveSearch];
                if (titleHeadResult.length>0) {
                    //判断原来的是否存在过
                    if (_searchArray.count == 0 || _searchArray == nil) {
                        RegisterModel *model = [self.tViewArray objectAtIndex:i];
                        [self.searchArray addObject:model];
                        
                    }
                    else
                    {
                        //这个地方还是有问题 当用首字母搜索的时候 有问题！！(忽略 已经不会走这个方法了)
                        for (int j = 0; j < [_searchArray count]; j++) {
                            RegisterModel *result = [_searchArray objectAtIndex:j];
                            
                            if ([[self.schoolInfo objectForKey:myKey] isEqualToString:result.name]) {
                                continue;
                            }
                            if (j == [self.searchArray count] - 1) {
                                
                                RegisterModel *model = [self.tViewArray objectAtIndex:i];
                                [self.searchArray addObject:model];
                            }
                        }
                    }
                    
                    
                }
                
            }
            //如果我的数据里都是拼音  就会走这个方法  遍历拼音  直接添加数组（想办法 直接跳到这里来，不走上面的方法 噢耶@！！！！）
            else {
                NSRange titleResult=[[self.schoolInfo objectForKey:myKey] rangeOfString:input.text options:NSCaseInsensitiveSearch];
                if (titleResult.length>0) {
                    RegisterModel *model = [self.tViewArray objectAtIndex:i];
                    [_searchArray addObject:model];
                }
                NSRange titleHeadResult=[[self.schoolHeadInfo objectForKey:myKey] rangeOfString:input.text options:NSCaseInsensitiveSearch];
                if (titleHeadResult.length>0) {
                    
                    RegisterModel *model = [self.tViewArray objectAtIndex:i];
                    [_searchArray addObject:model];
                    
                }
                
                
            }
        }//数组循环层
    }//最外层
    
    //汉字
    else if (input.text.length>0&&[ChineseInclude isIncludeChineseInString:input.text]) {
        for (RegisterModel *model in _tViewArray) {
            NSRange titleResult=[model.name rangeOfString:input.text options:NSCaseInsensitiveSearch];
            if (titleResult.length>0) {
                
                [_searchArray addObject:model];
            }
        }
    }
    
    [self.tableView reloadData];
    
    
    
    
    
}

@end
